package com.bluedot.dao;

import java.io.Serializable;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateDaoSupport<T, PK extends Serializable> implements
		Dao<T, PK> {
	private static SessionFactory sessionFactory;

	protected static SessionFactory getSessionFactory() {
		if (sessionFactory == null) {
			sessionFactory = new Configuration().configure()
					.buildSessionFactory();
		}
		return sessionFactory;
	}

	public static void closeSessionFactory() {
		if (sessionFactory != null) {
			sessionFactory.close();
		}
	}

	public static void initSession() {
		getSessionFactory().getCurrentSession().beginTransaction();
	}

	public Session getSession() {
		Session session=null;
		session=getSessionFactory().openSession();
		return session;
	}

	public static void rollback() {
		if (getSessionFactory().getCurrentSession() != null) {
			if (getSessionFactory().getCurrentSession().getTransaction() != null) {
				getSessionFactory().getCurrentSession().getTransaction()
						.rollback();
			}
		}
	}

	public static void commit() {
		if (getSessionFactory().getCurrentSession() != null) {
			if (getSessionFactory().getCurrentSession().getTransaction() != null) {
				getSessionFactory().getCurrentSession().getTransaction()
						.commit();
			}
		}
	}

	public static void close() {
		if (getSessionFactory().getCurrentSession() != null) {
			getSessionFactory().getCurrentSession().close();
		}
	}

	@SuppressWarnings("unchecked")
	protected Class entityClass;

	public void create(T entity) {
		Session session = this.getSession();
		session.save(entity);
	}

	public void delete(T entity) {
		Session session = this.getSession();
		session.delete(entity);
	}

	@SuppressWarnings("unchecked")
	@Override
	public T findById(PK id) {
		Session session = this.getSession();
		T entity = (T) session.get(this.entityClass, id);
		return entity;
	}

	@Override
	public void update(T entity) {
		Session session = this.getSession();
		session.update(entity);
	}

	@Override
	public void saveOrUpdate(T entity) {
		Session session = this.getSession();
		session.saveOrUpdate(entity);
	}

}
